package com.qiangzhi.service.impl;

import com.qiangzhi.constant.MessageConstant;
import com.qiangzhi.constant.StatusConstant;
import com.qiangzhi.pojo.dto.UserDTO;
import com.qiangzhi.pojo.dto.UserInfoDTO;
import com.qiangzhi.exception.BaseException;
import com.qiangzhi.mapper.CommonMapper;
import com.qiangzhi.pojo.po.UserInfoPO;
import com.qiangzhi.pojo.po.UserPO;
import com.qiangzhi.service.CommonService;
import com.qiangzhi.utils.AliOssUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class CommonServiceImpl implements CommonService {

    @Autowired
    private CommonMapper commonMapper;
    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 教务系统登录
     *
     * @param userDTO
     * @return
     */
    public UserPO login(UserDTO userDTO) {
        UserPO userPO = commonMapper.getByUserId(userDTO.getId(), userDTO.getIdentify());

        // 处理各种异常情况
        if (userPO == null) throw new BaseException(MessageConstant.ACCOUNT_NOT_FOUND); // 账号不存在

        // 账号被锁定
        if (StatusConstant.DISABLE.equals(userPO.getStatus())) throw new BaseException(MessageConstant.ACCOUNT_LOCKED);

        // 密码比对 对前端传过来的密码进行md5加密处理
        String password = DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes());
        if (!password.equals(userPO.getPassword())) throw new BaseException(MessageConstant.PASSWORD_ERROR);

        return userPO;
    }

    /**
     * 根据id修改用户密码
     *
     * @param userDTO
     * @return
     */
    public void updatePassword(UserDTO userDTO) {
        UserPO userPO = new UserPO();
        BeanUtils.copyProperties(userDTO, userPO);

        // 将前端传入的密码进行加密
        String password = DigestUtils.md5DigestAsHex(userPO.getPassword().getBytes());
        UserPO oldUserPO = commonMapper.getByUserId(userPO.getId(), userPO.getIdentify());

        // 新旧密码一致抛新旧密码相同异常
        if (oldUserPO.getPassword().equals(password)) throw new BaseException(MessageConstant.PASSWORD_EDIT_FAILED);

        userPO.setPassword(password);

        commonMapper.updatePassword(userPO);
    }

    /**
     * 根据jwt解析出的id编辑个人信息
     *
     * @param userInfoDTO
     * @return
     * @throws IOException
     */
    public void updateInfo(UserInfoDTO userInfoDTO) throws IOException {
        UserInfoPO userInfoPO = new UserInfoPO();
        BeanUtils.copyProperties(userInfoDTO, userInfoPO);

        // 获取上传的头像文件
        MultipartFile avatarFile = userInfoDTO.getAvatarFile();
        if (avatarFile != null && !avatarFile.isEmpty()) {
            // 文件不为空上传文件 并或得到上传后的文件路径
            String filePath = aliOssUtil.upload(avatarFile);
            // 设置头像文件路径
            userInfoPO.setAvatar(filePath);
        }

        commonMapper.updateInfo(userInfoPO);
    }

}
